# -*- coding:utf-8 -*-

__author__='zhaoxp'


'''
用元类来注解类的属性
'''


class Field(object):
    def __init__(self,name):
        self.name = name
        self.internal_name = '_' + self.name

    def __get__(self,instance,instance_type):
        if instance is None: return self
        return getattr(instance,self.internal_name,'')

    def __set__(self,instance,value):
        setattr(instance,self.internal_name,value)


class Customer(object):
    first_name = Field('first_name')
    last_name = Field('last_name')
    prefix = Field('prefix')
    suffix = Field('suffix')


class Field2(object):
    def __init__(self):
        self.name = None
        self.internal_name = None
    def __get__(self,instance,instace_type):
        if instance is None:return self
        return getattr(instance,self.internal_name,'')
    def __set__(self,instance,value):
        setattr(instance,self.internal_name,value)


class Meta(type):
    def __new__(meta,name,bases,class_dict):
        for key,value in class_dict.items():
            if isinstance(value,Field2):
                value.name = key
                value.internal_name = '_'+key
        return type.__new__(meta,name,bases,class_dict)


class BetterCustomer(object):
    __metaclass__ = Meta
    first_name = Field2()
    last_name = Field2()
    prefix = Field2()
    suffix = Field2()


if __name__=='__main__':
    print('Annotate Class Attributes with Metaclasses')
    foo = Customer()
    print('Before: %s %s'%(foo.first_name,foo.__dict__))
    foo.first_name = 'Euclid'
    print('After:  %s %s'%(foo.first_name,foo.__dict__))
    print('-'*30)
    foo = BetterCustomer()
    print('Before: %s %s'%(foo.first_name,foo.__dict__))
    foo.first_name = 'Euler'
    print('After:  %s %s'%(foo.first_name,foo.__dict__))
    

    